// ignore_for_file: dangling_library_doc_comments, slash_for_doc_comments
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common_code/extension/string_extension.dart';

import '../api/api_login.dart';

/*** 
 * @Author: Zhong
 * @Date: 2025-07-15 16:10:51
 * @LastEditors: Zhong zhongxiaodong@eenet.com
 * @LastEditTime: 2025-07-16 16:06:20
 * @FilePath: /wan_android_flutter/lib/module_code/login/pages/register_page.dart
 * @Description: 
 */

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  // 路由名称
  static const String routeName = '/register';

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  // appbar透明度
  double _appBarOpacity = 0.0;

  // 滚动监听
  final ScrollController _scrollController = ScrollController();

  //手机输入框controller
  final TextEditingController phoneTextEditController = TextEditingController();

  //密码输入框controller
  final TextEditingController pswTextEditController = TextEditingController();

  //确认密码输入框controller
  final TextEditingController rePswTextEditController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_updateAppBarOpacity);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('注册'),
        backgroundColor: Colors.blue.withOpacity(_appBarOpacity),
        elevation: 0, // 去除阴影
      ),
      extendBodyBehindAppBar: true, // 允许内容延伸到AppBar下方
      resizeToAvoidBottomInset: true,
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollUpdateNotification) {
            //更新透明度的值
            _updateAppBarOpacity();
          }
          return false;
        },
        child: GestureDetector(
          child: CustomScrollView(
            controller: _scrollController,
            physics: AlwaysScrollableScrollPhysics(),
            slivers: [
              SliverToBoxAdapter(child: _buildTopView()),
              SliverList(
                delegate: SliverChildListDelegate([
                  //主要内容视图
                  _buildBodyView(),
                ]),
              ),
            ],
          ),
          onTap: () {
            //点击空白区域收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          },
        ),
      ),
    );
  }

  //顶部视图
  Stack _buildTopView() {
    return Stack(
      children: [
        Container(
          width: double.infinity,
          height: 240.w,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/login_bg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Positioned(
          left: 30.w,
          bottom: 80.w,
          child: Image.asset('assets/images/登录页文字内容.png'),
        ),
        Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          child: Container(
            height: 20.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(10),
              ),
            ),
          ),
        ),
      ],
    );
  }

  //主要内容视图
  Container _buildBodyView() {
    return Container(
      width: double.infinity,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //手机号输入框
          _buildPhoneView(),
          //密码输入框
          _buildPswView(),
          //确定密码输入框
          _buildRePswView(),
          //注册按钮
          _buildRegisterBtn(),
        ],
      ),
    );
  }

  //手机号输入框
  Container _buildPhoneView() {
    return Container(
      color: Colors.white,
      height: 50,
      margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
      child: TextField(
        controller: phoneTextEditController,
        maxLength: 11,
        buildCounter:
            (
              context, {
              required currentLength,
              required isFocused,
              required maxLength,
            }) => null, //隐藏输入长度限制显示
        decoration: InputDecoration(
          //内容内边距，可设置光标起始位置，可让输入内容垂直居中
          contentPadding: const EdgeInsets.symmetric(vertical: 8.0),
          //框内左边内容
          prefixIcon: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              width: 50,
              height: 40,
              color: Colors.white,
              alignment: Alignment.center,
              child: Text.rich(
                TextSpan(
                  children: [
                    TextSpan(
                      text: '+86',
                      style: TextStyle(
                        color: Color(0xff030915),
                        fontSize: 14.sp,
                      ),
                    ),
                    TextSpan(
                      text: ' |',
                      style: TextStyle(
                        color: Color(0xffE2E2E2),
                        fontSize: 18.sp,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          labelText: '请输入手机号',
          labelStyle: TextStyle(color: Color(0xff999999)),
          //不展示浮动文字
          floatingLabelBehavior: FloatingLabelBehavior.never,
          //默认边框
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFE2E2E2), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
          //选中时的边框
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFF0082FE), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
        ),
        style: TextStyle(fontSize: 18.sp),
      ),
    );
  }

  //密码输入框
  Container _buildPswView() {
    return Container(
      color: Colors.white,
      height: 50,
      margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
      child: TextField(
        controller: pswTextEditController,
        maxLength: 6,
        buildCounter:
            (
              context, {
              required currentLength,
              required isFocused,
              required maxLength,
            }) => null, //隐藏输入长度限制显示
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.symmetric(
            vertical: 8.0,
            horizontal: 20,
          ), //可设置光标起始位置，可让文本垂直居中
          labelText: '请输入密码',
          labelStyle: TextStyle(color: Color(0xff999999)),
          //不展示浮动文字
          floatingLabelBehavior: FloatingLabelBehavior.never,
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFE2E2E2), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFF0082FE), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
        ),
        style: TextStyle(fontSize: 18.sp),
        obscureText: true, //密文显示
      ),
    );
  }

  //确定密码输入框
  Container _buildRePswView() {
    return Container(
      color: Colors.white,
      height: 50,
      margin: EdgeInsets.only(left: 30.w, right: 30.w, top: 20.w),
      child: TextField(
        controller: rePswTextEditController,
        maxLength: 6,
        buildCounter:
            (
              context, {
              required currentLength,
              required isFocused,
              required maxLength,
            }) => null, //隐藏输入长度限制显示
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.symmetric(
            vertical: 8.0,
            horizontal: 20,
          ), //可设置光标起始位置，可让文本垂直居中
          labelText: '请再次输入密码',
          labelStyle: TextStyle(color: Color(0xff999999)),
          //不展示浮动文字
          floatingLabelBehavior: FloatingLabelBehavior.never,
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFE2E2E2), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFF0082FE), width: 0.5),
            borderRadius: BorderRadius.all(Radius.circular(25)),
          ),
        ),
        style: TextStyle(fontSize: 18.sp),
      ),
    );
  }

  //注册按钮
  Container _buildRegisterBtn() {
    return Container(
      margin: EdgeInsets.only(top: 50, left: 30, right: 30),
      width: double.infinity,
      height: 50.w,
      child: ElevatedButton(
        onPressed: () {
          //点击登录
          _requestRegister(
            mobile: phoneTextEditController.text,
            psw: pswTextEditController.text,
            rePsw: rePswTextEditController.text,
          );
        },
        style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
        child: Text(
          '注册',
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  //点击登录
  void _requestRegister({
    required String mobile,
    required String psw,
    required String rePsw,
  }) async {
    if (!mobile.isValidPhoneNumber) {
      EasyLoading.showToast('请输入正确手机号！');
      return;
    }

    if (psw.isEmpty) {
      EasyLoading.showToast('请输入验证码！');
      return;
    }

    if (psw != rePsw) {
      EasyLoading.showToast('两次输入的密码不一致！');
      return;
    }

    bool isSuc = await ApiLogin.register(
      username: mobile,
      password: psw,
      rePassword: rePsw,
    );
    if (isSuc) {
      EasyLoading.showToast('注册成功，即将跳转登录页面！');
      //延时2秒返回上一个页面
      Future.delayed(Duration(seconds: 2), () {
        Get.back();
      });
    }
  }

  // navigationBar透明度
  void _updateAppBarOpacity() {
    final offset = _scrollController.offset;
    setState(() {
      _appBarOpacity = offset / 100; // 200是透明度变化的临界值
      if (_appBarOpacity > 1.0 || _appBarOpacity < -1.0) _appBarOpacity = 1.0;
      if (_appBarOpacity < 0.0) _appBarOpacity = _appBarOpacity.abs();
    });
  }
}
